package com.hualan.listener;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.util.DruidWebUtils;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

@WebListener
public class RequestListener implements ServletRequestListener {
    private Connection conn;

    private static final DataSource comboPooledDataSource;

    static {
        try {
            InputStream resourceStream = DruidWebUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
            Properties properties = new Properties();
            properties.load(resourceStream);
            comboPooledDataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        HttpServletRequest req = (HttpServletRequest) sre.getServletRequest();
        if(!req.getServletPath().endsWith(".html")&&!req.getServletPath().endsWith(".htm")) {
            try {
                this.conn = comboPooledDataSource.getConnection();
                conn.setAutoCommit(false);
                sre.getServletRequest().setAttribute("conn", this.conn);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        HttpServletRequest req = (HttpServletRequest) sre.getServletRequest();
        if(!req.getServletPath().endsWith(".html")&&!req.getServletPath().endsWith(".htm")) {
            try {
                this.conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
